<template>
	<view class="form-container bg">
		<u-sticky>
            <view style="background: #fff;">
                <view class="flex-center padding-top-10">
                    <view class="machine-title">
                        <view>{{ruleForm.machineName}}</view>
                    </view>
                </view>
                <u-subsection :list="tabList" :current="activeTab" model="button" fontSize="18" @change="onTabChange"></u-subsection>
            </view>
		</u-sticky>
        <view v-if="taskList.length > 0" class="margin-top-20">
            <u-alert :description="`当前存在${taskList.length}个开台但未了机的任务,请酌情开台!`" fontSize="16" type="warning" :showIcon="true"></u-alert>
        </view>
        <view v-if="activeTab === 0" class="margin-top-30">
            <jkFormCard title="仪表信息">
                <jk-form-item label="开台时间" :show-star="true" @click="onUpdateTime" :value="ruleForm.startSystemTime" @clear="onDeleteTime">
                    <view>{{ ruleForm.startSystemTime || '' }}</view>
                </jk-form-item>
                <jk-form-item label="开台班次" :show-right-icon="false">
                    <view>{{ ruleForm.startScheduleShiftName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="开台锭数" :show-star="true" :value="ruleForm.openSpinCount" @clear="ruleForm.openSpinCount = ''" right-icon="edit-pen">
                    <u-input v-model="ruleForm.openSpinCount" @blur="onTransferNumber($event, 'openSpinCount')" :customStyle="{paddingLeft: 0}" fontSize="28rpx" inputAlign="left" type="number" placeholder="开台锭数" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="系数" :show-star="true" :value="ruleForm.outputRatio" @clear="ruleForm.outputRatio = ''" right-icon="edit-pen">
                    <u-input v-model="ruleForm.outputRatio" @blur="onTransferNumber($event, 'outputRatio')" :customStyle="{paddingLeft: 0}" type="digit" fontSize="28rpx" inputAlign="left" placeholder="系数" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="开台产量表数" :show-star="true" :value="ruleForm.startOutput" @clear="ruleForm.startOutput = ''" right-icon="edit-pen">
                    <u-input v-model="ruleForm.startOutput" @blur="onTransferNumber($event, 'startOutput')" type="digit" :customStyle="{paddingLeft: 0}" fontSize="28rpx" inputAlign="left" placeholder="开台产量表数" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="产量采集表数" :show-right-icon="false">
                    <view>{{ ruleForm.startSystemOutput || '' }}</view>
                </jk-form-item>
                <jk-form-item label="开台能耗表数" :show-star="true" :value="ruleForm.startElectricEnergy" @clear="ruleForm.startElectricEnergy = ''" right-icon="edit-pen">
                    <u-input v-model="ruleForm.startElectricEnergy" type="digit" @blur="onTransferNumber($event, 'startElectricEnergy')" :customStyle="{paddingLeft: 0}" fontSize="28rpx" inputAlign="left" placeholder="开台能耗表数" border="surround"></u-input>
                </jk-form-item>
                <jk-form-item label="能耗采集表数" :show-right-icon="false">
                    <view>{{ ruleForm.startSystemElectricEnergy || '' }}</view>
                </jk-form-item>
            </jkFormCard>
        </view>
        <view v-if="activeTab === 1" class="margin-top-30">
            <jkFormCard title="排产信息">
                <jk-form-item label="开台产品" :show-right-icon="false">
                    <view>{{ ruleForm.productName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="生产批号" :show-right-icon="false">
                    <view>{{ ruleForm.batchCode || '' }}</view>
                </jk-form-item>
                <jk-form-item label="排产数量" :show-right-icon="false">
                    <view>{{ ruleForm.productionQty || '' }}</view>
                </jk-form-item>
                <jk-form-item label="通知单号" :show-right-icon="false">
                    <view>{{ ruleForm.prdNoticeCode || '' }}</view>
                </jk-form-item>
                <jk-form-item label="所属工序" :show-right-icon="false">
                    <view>{{ ruleForm.processName || '' }}</view>
                </jk-form-item>
                <jk-form-item label="所属车间" :show-right-icon="false">
                    <view>{{ ruleForm.workshopName || '' }}</view>
                </jk-form-item>
            </jkFormCard>
        </view>
        <!--<u-form labelPosition="left" :model="ruleForm" :rules="rules" labelWidth="180px" ref="ruleForm" :labelStyle="{height: '64rpx',fontSize: '28rpx'}">
			&lt;!&ndash; 产量能耗信息 &ndash;&gt;
			<u-form-item v-if="activeTab === 0" label="开台时间" labelWidth="120px" prop="machineName" borderBottom
				ref="item1">
				<view class="flex-end-center font-size-16 width-100-percentage" @click="onUpdateTime">
					<view class="item-gap" style="color: #2d8cf0;">{{ ruleForm.startSystemTime }}</view>
				</view>
			</u-form-item>
			<u-form-item v-if="activeTab === 0" label="开台班次" borderBottom ref="item1">
				<view class="text-right font-size-16 width-100-percentage">{{ ruleForm.startScheduleShiftName }}</view>
			</u-form-item>
			<u-form-item v-if="activeTab === 0" label="开台锭数" borderBottom ref="item1">
				<u-input v-model="ruleForm.openSpinCount" color="#2d8cf0" fontSize="32rpx" inputAlign="right" type="number" placeholder="开台锭数" border="surround"></u-input>
			</u-form-item>
            <u-form-item v-if="activeTab === 0" label="系数" borderBottom ref="item1">
                <u-input v-model="ruleForm.outputRatio" @blur="onOutputRatioBlur" type="digit" color="#2d8cf0" fontSize="32rpx" inputAlign="right" placeholder="系数" border="surround"></u-input>
            </u-form-item>
			<u-form-item v-if="activeTab === 0" label="开台产量表数" borderBottom ref="item1">
				<u-input v-model="ruleForm.startOutput" color="#2d8cf0" fontSize="32rpx" inputAlign="right" type="digit" placeholder="开台产量表数" border="surround"></u-input>
			</u-form-item>
			<u-form-item v-if="activeTab === 0" label="产量采集表数" borderBottom ref="item1">
				<view class="text-right font-size-16 width-100-percentage">{{ ruleForm.startSystemOutput }}</view>
			</u-form-item>
			<u-form-item v-if="activeTab === 0" label="开台能耗表数" borderBottom ref="item1">
				<u-input v-model="ruleForm.startElectricEnergy" color="#2d8cf0" fontSize="32rpx" inputAlign="right" type="digit" placeholder="开台能耗表数" border="surround"></u-input>
			</u-form-item>
			<u-form-item v-if="activeTab === 0" label="能耗采集表数" borderBottom ref="item1">
				<view class="text-right font-size-16 width-100-percentage">{{ ruleForm.startSystemElectricEnergy }}</view>
			</u-form-item>
		</u-form>-->
		<view class="fixed-footer">
			<u-button @click="onConfirmBtn" color="#2d8cf0" :loading="confirmLoading" size="large">确定</u-button>
		</view>
		<jk-popup :show="showXsPopup" title="细纱管颜色" @close="onCloseXsPopup">
			<u-checkbox-group v-model="ruleForm.spunYarnColorIds" size="21" iconPlacement="right" placement="column"
				:borderBottom="true" @change="onXsCheckboxChange">
				<view style="height: 400px;overflow: auto;">
					<u-checkbox v-for="item in xsTubeColorList" :key="item.id" labelSize="18" iconSize="20"
						:borderBottom="true" :customStyle="{
                    margin: '8rpx',
                }" :label="item.name" :name="item.id" style="margin: 10rpx;"></u-checkbox>
				</view>
			</u-checkbox-group>
		</jk-popup>
		<jk-popup :show="showCsPopup" title="粗纱管颜色" @close="onCloseCsPopup">
			<u-checkbox-group v-model="ruleForm.rovingColorIds" size="21" iconPlacement="right" placement="column"
				:borderBottom="true" @change="onCsCheckboxChange">
				<view style="height: 400px;overflow: auto;">
					<u-checkbox v-for="item in csTubeColorList" :key="item.id" labelSize="18" iconSize="20"
						:borderBottom="true" :customStyle="{
                    margin: '8rpx',
                }" :label="item.name" :name="item.id" style="margin: 10rpx;"></u-checkbox>
				</view>
			</u-checkbox-group>
		</jk-popup>
		<u-datetime-picker v-model="selectDateTime" :show="selectDateTimePickerState" mode="datetime"
			:closeOnClickOverlay="true" @confirm="onConfirmBtnOfSelectPicker" @close="onCloseBtnOfSelectPicker"
			@cancel="onCloseBtnOfSelectPicker"></u-datetime-picker>
	</view>
</template>

<script>
import {
    productionPrdNoticeMachineChangeGet,
    productionPrdNoticeMachineChangeGetMachineData, productionPrdNoticeMachineChangePage,
    productionPrdNoticeMachineOpeningCompleteRenovationOpening,
    productionPrdNoticeMachineOpeningOpening,
    tubeColorList,
    workforcemanagementScheduleShiftByTime
} from "../../../api";
	import {
		formatTime,
		showLoading
	} from "../../../utils/jk-utils";
	import jkPopup from '../../../jk-components/jk-popup/index';
import jkFormCard from "../../../jk-components/jk-from-card";
import jkFormItem from "../../../jk-components/jk-from-item";
	export default {
		components: {
            jkFormCard,
            jkFormItem,
			jkPopup
		},
		data() {
			return {
                taskList: [],
				selectDateTime: '',
				selectDateTimePickerState: false,
				confirmLoading: false,
				activeTab: 0,
				tabList: ['仪表信息', '排产信息'],
				showCsPopup: false,
				showXsPopup: false,
				xsTubeColorList: [],
				csTubeColorList: [],
				dataId: null,
				ruleForm: {
					startSystemTime: '',
					spunYarnColorIds: [], // 细纱管颜色
					spunYarnColorNames: [],
					rovingColorIds: [], // 粗纱管颜色
					rovingColorNames: [],
					machineCode: '',
					workshopId: null,
					workshopName: '',
					processId: null,
					processName: '',
                    startScheduleShiftName: '',
					startState: 0,
                    outputRatio: 1
				},
				rules: {
					machineName: {
						type: 'string',
						required: true,
						message: '请填写设备',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onLoad(e) {
			this.dataId = e.id;
		},
		onShow() {
			this.getDependentData();
		},
		methods: {
            onTransferNumber(e, type) {
                this.$set(this.ruleForm, type, Number(e));
            },
		    onDeleteTime() {
                this.$set(this.ruleForm, 'startSystemTime', null);
                this.$set(this.ruleForm, 'startScheduleShiftId', null);
                this.$set(this.ruleForm, 'startScheduleShiftName', '');
                // 开台能耗表数，默认等于采集到的实时能耗
                this.$set(this.ruleForm, 'startElectricEnergy', null);
                this.$set(this.ruleForm, 'startSystemElectricEnergy', null);
                // 开台产量表数，默认等于采集到的实时产量
                this.$set(this.ruleForm, 'startOutput', null);
                this.$set(this.ruleForm, 'startSystemOutput', null);
                // 上次的产量和能耗
                this.$set(this.ruleForm, 'lastEndOutput', null);
                this.$set(this.ruleForm, 'lastEndElectricEnergy', null);

                this.$set(this.ruleForm, 'openSpinCount', null);
                this.$set(this.ruleForm, 'outputRatio', 1);
            },
            onOutputRatioBlur(e) {
                if (e > 1) {
                    this.$set(this.ruleForm, 'outputRatio', 1);
                }
            },
			onUpdateTime() {
				this.selectDateTimePickerState = true;
			},
			onCloseBtnOfSelectPicker() {
				this.selectDateTimePickerState = false;
			},
			onConfirmBtnOfSelectPicker(e) {
				this.$set(this.ruleForm, 'startSystemTime', formatTime(e.value));
				this.selectDateTimePickerState = false;
				this.getGatherMachineDataRequest();
				this.getScheduleShiftForTimeRequest();
			},
			onConfirmBtn() {
                if (this.ruleForm.startSystemTime && this.ruleForm.openSpinCount && this.ruleForm.outputRatio && this.ruleForm.startOutput && this.ruleForm.startElectricEnergy) {
                    this.confirmLoading = true;
                    this.ruleForm.prdNoticeMachineChangeId = this.dataId;
                    let params = JSON.parse(JSON.stringify(this.ruleForm));
                    productionPrdNoticeMachineOpeningOpening({
                        "endSpinNumber": 0,
                        "lastEndElectricEnergy": params.lastEndElectricEnergy,
                        "lastEndOutput": params.lastEndOutput,
                        "openSpinCount": params.openSpinCount,
                        "prdNoticeMachineChangeId": params.prdNoticeMachineChangeId,
                        "startElectricEnergy": params.startElectricEnergy,
                        "startOutput": params.startOutput,
                        "outputRatio": params.outputRatio,
                        "startScheduleShiftId": params.startScheduleShiftId,
                        "startSpinNumber": params.startSpinNumber,
                        "startSystemElectricEnergy": params.startSystemElectricEnergy,
                        "startSystemOutput": params.startSystemOutput,
                        "startSystemTime": params.startSystemTime
                    }).then(res => {
                        this.confirmLoading = false;
                        if (res.data.status === 200) {
                            uni.navigateBack({
                                delta: 1
                            });
                            uni.showToast({
                                title: '保存成功!'
                            });
                        }
                    })
                } else {
                    uni.showToast({
                        title: '请填写完成',
                        icon: 'error'
                    });
                }
			},
			onTabChange(e) {
				this.activeTab = e;
			},
			onCloseCsPopup() {
				this.showCsPopup = false;
			},
			onCsCheckboxChange(e) {
				this.ruleForm.rovingColorNames = [];
				e.forEach(x => {
					this.csTubeColorList.forEach(k => {
						if (x === k.id) {
							this.ruleForm.rovingColorNames.push(k.name);
						}
					})
				})
			},
			onXsCheckboxChange(e) {
				this.ruleForm.spunYarnColorNames = [];
				e.forEach(x => {
					this.xsTubeColorList.forEach(k => {
						if (x === k.id) {
							this.ruleForm.spunYarnColorNames.push(k.name);
						}
					})
				})
			},
			onCloseXsPopup() {
				this.showXsPopup = false;
			},
			onSelectXsTubeColor() {
				let _this = this;
				uni.showActionSheet({
					itemList: _this.xsTubeColorList.map(x => x.name),
					success(res) {
						_this.$set(_this.ruleForm, 'spunYarnColorIds', _this.xsTubeColorList[res.tapIndex].id);
						_this.$set(_this.ruleForm, 'spunYarnColorName', _this.xsTubeColorList[res.tapIndex].name);
						_this.getListRequest();
					}
				});
			},
			// 细纱管颜色
			getXsTubeColorListRequest() {
				return tubeColorList({
					auditState: 3,
					typeCode: "001"
				}).then(res => {
					if (res.data.status === 200) {
						this.xsTubeColorList = res.data.res;
					}
				})
			},
			// 粗纱管颜色
			getCsTubeColorListRequest() {
				return tubeColorList({
					auditState: 3,
					typeCode: "002"
				}).then(res => {
					if (res.data.status === 200) {
						this.csTubeColorList = res.data.res;
					}
				})
			},
			// 获取指定机台采集的仪表数据
			getGatherMachineDataRequest() {
				if (this.ruleForm.machineId && this.ruleForm.machineCode) {
					return productionPrdNoticeMachineChangeGetMachineData({
						machineId: this.ruleForm.machineId,
						machineCode: this.ruleForm.machineCode,
						selectDateTime: this.ruleForm.startSystemTime
					}).then(res => {
						if (res.data.status === 200) {
							// 开台能耗表数，默认等于采集到的实时能耗
							this.$set(this.ruleForm, 'startElectricEnergy', res.data.res.currentElectricEnergy);
							this.$set(this.ruleForm, 'startSystemElectricEnergy', res.data.res
								.currentElectricEnergy);
							// 开台产量表数，默认等于采集到的实时产量
							this.$set(this.ruleForm, 'startOutput', res.data.res.currentOutput);
							this.$set(this.ruleForm, 'startSystemOutput', res.data.res.currentOutput);
							// 上次的产量和能耗
							this.$set(this.ruleForm, 'lastEndOutput', res.data.res.lastEndOutput);
							this.$set(this.ruleForm, 'lastEndElectricEnergy', res.data.res.lastEndElectricEnergy);

                            this.$set(this.ruleForm, 'openSpinCount', res.data.res.spinCount);
                            this.$set(this.ruleForm, 'outputRatio', 1);
						}
					});
				}
			},
			getScheduleShiftForTimeRequest() {
				if (this.ruleForm.workshopId && this.ruleForm.startSystemTime) {
					return workforcemanagementScheduleShiftByTime({
						startTime: formatTime(this.ruleForm.startSystemTime),
						workshopId: this.ruleForm.workshopId
					}).then(res => {
						if (res.data.status === 200) {
							let resData = res.data.res || {};
							this.$set(this.ruleForm, 'startScheduleShiftId', resData.shiftId);
							this.$set(this.ruleForm, 'startScheduleShiftName', resData.shiftName);
						}
					});
				}
			},
			getDetailRequest() {
				return productionPrdNoticeMachineChangeGet({
					id: this.dataId
				}).then(res => {
					if (res.data.status === 200) {
						this.ruleForm = res.data.res;
					}
				})
			},
            getMachineTaskRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.machineCode) {
                    return productionPrdNoticeMachineChangePage({
                        openingState: 3,
                        workshopId: this.ruleForm.workshopId,
                        machineNameOrCode: this.ruleForm.machineCode
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.taskList = res.data.res;
                        }
                    })
                }
            },
			async getDependentData() {
				showLoading(true);
				// await this.getXsTubeColorListRequest();
				if (this.dataId) await this.getDetailRequest();
				this.selectDateTime = formatTime(Date.now());
				this.$set(this.ruleForm, 'startSystemTime', formatTime(Date.now()));
				await this.getScheduleShiftForTimeRequest();
				// await this.getCsTubeColorListRequest();
				await this.getGatherMachineDataRequest();
				await this.getMachineTaskRequest();
				showLoading(false);
			}
		}
	}
</script>

<style>

</style>
<style lang="scss" scoped>
	.machine-title {
		height: 42px;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2d8cf0;
		border-radius: 12rpx;
		padding: 12rpx 24rpx;
		box-sizing: border-box;
        //background: #2d8cf0;
        border: solid 1px #2d8cf0;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		margin: 10rpx;
	}

	.popup-content-box {
		padding: 32rpx;

		.popup-content-box-title {
			font-size: 34rpx;
			text-align: center;
			margin-bottom: 20rpx;
		}
	}
</style>
